package com.lxyk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxyk.yygh.common.exception.YyghException;
import com.lxyk.yygh.common.helper.HttpRequestHelper;
import com.lxyk.yygh.common.rabbit.constant.MqConst;
import com.lxyk.yygh.common.rabbit.service.RabbitService;
import com.lxyk.yygh.common.result.ResultCodeEnum;
import com.lxyk.yygh.enums.OrderStatusEnum;
import com.lxyk.yygh.model.order.OrderInfo;
import com.lxyk.yygh.model.user.Patient;
import com.lxyk.yygh.order.mapper.OrderMapper;
import com.lxyk.yygh.order.service.OrderService;
import com.lxyk.yygh.order.service.RefundInfoService;
import com.lxyk.yygh.order.service.WeixinService;
import com.lxyk.yygh.user.client.HospFeignClient;
import com.lxyk.yygh.user.client.UserFeignClient;
import com.lxyk.yygh.vo.hosp.ScheduleOrderVo;
import com.lxyk.yygh.vo.msm.MsmVo;
import com.lxyk.yygh.vo.order.*;
import org.joda.time.DateTime;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Time;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    //远程调用
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private HospFeignClient hospFeignClient;

    //rabbit
    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WeixinService weixinService;

    //redis
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //  生产订单的逻辑：
    //	根据就诊人的id （patientId）得到信息，在根据排版id（scheduleId）得到信息
    //                然后把信息加到数据库中，我们去调用医院的接口，在医院那边做订单生成，医院接口那边会返回数据
    //	得到返回数据，来更新订单表中的内容，这就是流程。

    //生成挂号订单
    //事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        ////获取就诊人信息
        Patient patient = userFeignClient.getPatientById(patientId);
        //获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo(scheduleId);

        //判断当前时间是否还可以预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            //当前时间不可以预约
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        HashOperations<String,String,Integer> hashOps = redisTemplate.opsForHash();
        int available_number = hashOps.get(scheduleId, "available_number");
        int reserved_number = hashOps.get(scheduleId, "reserved_number");
//        创建分布式锁
        String lockName="schedule_lock:"+scheduleId;
        RLock lock = redissonClient.getLock(lockName);
        try {
            //尝试加锁,最多等待10s,自动解锁,1h后自动解锁
            boolean isLocked = lock.tryLock(20, 1*60*60, TimeUnit.SECONDS);

            if (available_number <= 0) {
                throw new YyghException("当前时间段号源不足，请选择其他时间段", 222);
            }

//            如果加锁成功
            if(isLocked){

        //进行挂号
        //号源充足的情况下
        //获取签名信息
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        //添加道订单表
        OrderInfo orderInfo = new OrderInfo();   // scheduleOrderVo中的数据  复制到  orderInfo
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);

        //向 orderInfo设置其他数据
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);//订单号根据当前时间随机
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        /**
         * UNPAID(0,"预约成功，待支付"),
         * PAID(1,"已支付" ),
         * GET_NUMBER(2,"已取号" ),
         * CANCLE(-1,"取消预约"),
         */
        //预约成功,待支付
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //调用医院接口，实现预约挂号操作
        //====设置调用医院接口需要的参数，参数放到map集合中====
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        //请求医院模拟系统
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        System.out.println("===================医院模拟系统result============");
        System.out.println("============result" + result);
        System.out.println("===================医院模拟系统result============");
        //result 是一个json对象

        //状态码
        if (result.getInteger("code") == 200) {

            hashOps.increment(scheduleId,"available_number",-1);
            hashOps.increment(scheduleId,"reserved_number",1);

            baseMapper.insert(orderInfo);
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            // TODO: 发送mq信息更新号源和短信通知   后期来处理
            //发送mq信息更新号源和短信通知
            //发送mq信息更新号源 mongdb的schedule数据
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            //短信模板code
            // TODO: 这里的短信上线需要修改
            msmVo.setTemplateCode("SMS_462265090");
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};

            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            //发送,这是往订单交换机，订单routingkey,发送orderMqVo,orderMqVo里面有msmVo
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

            //在医院这边有记录了
//            延时队列实现十分钟后订单取消
            rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_DELAY,MqConst.ROUTING_DELAY,orderInfo,
                    message -> {message.getMessageProperties().setDelay(1*60*1000);
                    return message;
            });//最后一个参数是消息后置处理器，设置过期时间


        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();   //返回订单号
}

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();//解锁
            return null;
        }
    }


// 定时任务，处理等待队列中的预约请求
//    @Scheduled(fixedRate = 5000) // 每 5 秒执行一次
//    public void processWaitingOrders() {
//        // 从 Redis 中获取所有等待队列的 key
//        Set<String> waitingListKeys = redisTemplate.keys("waiting_orders:*");
//
//    }

//    根据订单id查询订单详情
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //包装后在返回
        return this.packOrderInfo(orderInfo);
    }

    //订单列表（条件查询带分页）
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人id
        //String patientName = orderQueryVo.getPatientName();  //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    //后台
    //订单详情
    //这是根据订单id而不是订单号进行查询
    @Override
    public Map<String, Object> show(Long orderId) {
        Map<String, Object> map = new HashMap<>();
        OrderInfo orderInfo = this.packOrderInfo(this.getById(orderId));
        map.put("orderInfo", orderInfo);
        Patient patient
                =  userFeignClient.getPatientById(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    //取消预约，退款
    @Override
    public Boolean cancelOrder(Long orderId) {
        //根据id获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        String scheduleId = orderInfo.getScheduleId();
        if(orderInfo==null){
            throw  new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        Date quitTime = orderInfo.getQuitTime();
        //判断时间是否可以退号
        //如果当前时间大于退号时间，不能取消预约 时间已经过了
        if(new DateTime(quitTime).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        //3、调用医院接口实现预约取消
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        //signInfoVo.getApiUrl()--->http://localhost:9998/
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");
        //4、根据医院接口返回数据进行操作
        if(result.getInteger("code")!=200){
            throw new YyghException(result.getString("message"),ResultCodeEnum.FAIL.getCode());
        }else{

            //else表示医院那边调用成功   如果医院调用成功，则我们调用微信退款的方法然后进行相关的操作

            //判断当前是否可以退款
            // PAID(1,"已支付" ),支付了
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()){
                //执行退款操作
                Boolean isRefund = weixinService.refund(orderId);
                //false退款失败
                if(!isRefund) {
                    //没有付款 就还是更改订单，一样的操作
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                //更改订单状态    把订单状态改为：取消预约  -1
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);
//                更新redis的数量
                HashOperations<String,String,Integer> hashOps = redisTemplate.opsForHash();
                hashOps.increment(scheduleId,"available_number",1);
                hashOps.increment(scheduleId,"reserved_number",-1);

                //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，
                //不设置可预约数与剩余预约数，接收端可预约数减1即可,取消+1
                //这个修改的是
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());
                //短信提示
                // TODO: 这个短信上线需要修改，个人无法申请
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                msmVo.setTemplateCode("SMS_268595197");
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
                Map<String,Object> param = new HashMap<String,Object>(){{
                    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            }else{
                //还没有支付
                //更改订单状态    把订单状态改为：取消预约  -1
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);
                //更新redis的数量
                HashOperations<String,String,Integer> hashOps = redisTemplate.opsForHash();
                hashOps.increment(scheduleId,"available_number",1);
                hashOps.increment(scheduleId,"reserved_number",-1);

                //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，
                //不设置可预约数与剩余预约数，接收端可预约数减1即可,取消+1
                //这个修改的是
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());
                //短信提示
                // TODO: 这个短信上线需要修改，个人无法申请
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                msmVo.setTemplateCode("SMS_268595197");
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
                Map<String,Object> param = new HashMap<String,Object>(){{
                    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            }
            return true;
        }
    }

    //就诊提醒通知
    @Override
    public void patientTips() {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getReserveDate,new DateTime().toString("yyyy-MM-dd"));//安排
        //ne 订单状态不等于-1 -1取消预约
        lambdaQueryWrapper.ne(OrderInfo::getOrderStatus,OrderStatusEnum.CANCLE.getStatus());
        //查询
        List<OrderInfo> orderInfoList = baseMapper.selectList(lambdaQueryWrapper);
        //遍历集合发送短信
        for(OrderInfo orderInfo:orderInfoList){
            //短信提示
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            //发的msmVo喽
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }

    }
    //预约订单统计
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {

        //调用mapper方法得到数据
        List<OrderCountVo> orderCountVoList = baseMapper.selectOrderCount(orderCountQueryVo);

        //获取x轴 需要的数据 ，日期数据  list集合
        //日期列表
        List<String> dateList=orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        System.out.println("dateList"+dateList);
        //获取y轴 需要的数据 ，具体数量  list集合
        //统计列表
        List<Integer> countList = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList()); Map<String, Object> map = new HashMap<>();
        System.out.println("countList"+countList);
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }


    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}